﻿@page "/login"

@using MaBlaApp.Data

@layout LoginLayout

<div class="d-flex justify-content-center">

    <div class="card" style="width:500px">

        <div class="card-header">
            <h5>
                手机验证码登录
            </h5>
        </div>

        <div class="card-body">

            <div class="form-group form-inline">
                <label for="PhoneNumber" class="control-label">手机号</label>
                <input id="PhoneNumber" @bind="PhoneNumber" class="form-control" placeholder="请输入手机号" />
            </div>

            <div class="form-group form-inline">
                <label for="VerificationCode" class="control-label">验证码</label>
                <input id="VerificationCode" @bind="VerificationCode" class="form-control" placeholder="请输入验证码" />
                @if (CanGetVerificationCode)
                {
                    <button type="button" class="btn btn-link" @onclick="GetVerificationCode">
                        获取验证码
                    </button>
                }
                else
                {
                    <label>@GetVerificationCodeMsg</label>
                }
            </div>

        </div>

        <div class="card-footer">
            <button type="button" class="btn btn-primary" @onclick="Login">
                登录
            </button>
        </div>

    </div>
</div>

@code {

    [Inject]
    private Ids4Client ids4Client { get; set; }

    [Inject]
    private NavigationManager navigationManager { get; set; }

    [Inject]
    private LoginUserManager loginUserManager { get; set; }

    private string PhoneNumber;

    private string VerificationCode;

    //获取验证码按钮当前状态
    private bool CanGetVerificationCode = true;

    private string GetVerificationCodeMsg;

    //获取验证码
    private async void GetVerificationCode()
    {
        if (CanGetVerificationCode)
        {
            //发送验证码到手机号
            string result = await ids4Client.SendPhoneCodeAsync(PhoneNumber);

            if (result != "发送验证码成功")
                return;

            CanGetVerificationCode = false;

            //1分钟倒计时
            for (int i = 60; i >= 0; i--)
            {
                GetVerificationCodeMsg = $"获取验证码({i})";

                await Task.Delay(1000);

                //通知页面更新
                StateHasChanged();
            }

            CanGetVerificationCode = true;

            //通知页面更新
            StateHasChanged();
        }
    }

    //登录
    private async void Login()
    {
        //手机验证码登录
        var userInfo = await ids4Client.PhoneCodeLogin(PhoneNumber, VerificationCode);

        //登录
        loginUserManager.Login(userInfo);

        //跳转回主页
        navigationManager.NavigateTo("/");
    }
}
